import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '@/store/index';
import useRequest from '@/hooks/useRequest';
import { syncCurrentUserState } from '@/store/user';
import { fetchUserInfo } from '@/services/user';

export default function useAutoSyncUserState() {
    const dispatch: AppDispatch = useDispatch();
    const token = useSelector((state: RootState) => state.user.auth?.token);
    const { run } = useRequest(async () => {
        const { data, status } = await fetchUserInfo();

        if (status !== 0) {
            return;
        }

        dispatch(syncCurrentUserState(data));
    });
    useEffect(() => {
        if (!token) return;
        run();
    }, [token]);
}
